package com.dreamlin.okhttp;

import androidx.annotation.NonNull;

import com.google.gson.Gson;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public enum OkHttpHelper {

    INSTANCE;

    private OkHttpClient okHttpClient;

    private Gson gson;

    OkHttpHelper() {
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(30000, TimeUnit.MILLISECONDS)
                .writeTimeout(30000, TimeUnit.MILLISECONDS)
                .connectTimeout(30000, TimeUnit.MILLISECONDS)
                .callTimeout(30000, TimeUnit.MILLISECONDS);
        HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor();
        httpLoggingInterceptor.level(HttpLoggingInterceptor.Level.BODY);
        builder.addInterceptor(httpLoggingInterceptor);
        okHttpClient = builder.build();
        gson = new Gson();
    }

    private Retrofit newRetrofit(@NonNull String baseUrl) {
        Retrofit.Builder builder = new Retrofit.Builder();
        builder.baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create());
        return builder.build();
    }

    public Api apiService(@NonNull String baseUrl) {
        return newRetrofit(baseUrl).create(Api.class);
    }

}
